package com.zbkj.client.aspect;

import com.zbkj.client.annotation.Token;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.result.CommonResult;
import com.zbkj.common.utils.RedisUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Aspect
@Component
public class TokenAspect {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    @Around("@annotation(token)")
    public Object checkToken(ProceedingJoinPoint joinPoint, Token token) throws Throwable {
        String tokenValue = request.getHeader("token");
        if (tokenValue == null || tokenValue.isEmpty()) {
//            response.setStatus(HttpStatus.UNAUTHORIZED.value());
//            response.setContentType("application/json;charset=UTF-8");
//            response.getWriter().write("{\"code\":401,\"msg\":\"未登录，请先登录\"}");
//            return null;

            response.setStatus(401);
            return CommonResult.failed("请先登录");
        }
        String redisKey = "T:" + tokenValue;
        Object userId = redisUtil.get(redisKey);
        if (userId == null) {
//            response.setStatus(HttpStatus.UNAUTHORIZED.value());
//            response.setContentType("application/json;charset=UTF-8");
//            response.getWriter().write("{\"code\":401,\"msg\":\"登录已失效，请重新登录\"}");
//            return null;

            response.setStatus(401);
            return CommonResult.failed("请先登录");

        }
        // 可将userId放入ThreadLocal，便于后续获取
        // UserHolder.setUserId((Integer) userId);
        return joinPoint.proceed();
    }
} 